package com.youxiake.lock;


import lombok.extern.slf4j.Slf4j;

/**
 * 自己实现一个不可冲入锁
 * @author jxbai
 * @date 2021/12/14
 */
public class NonReentrantLockDemo implements Runnable{

    NonReentrantLock lock = new NonReentrantLock();

    @Override
    public void run() {
        try {
            set();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void set() throws InterruptedException {
        lock.lock();
        try {
            System.out.println("set方法");
            get();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void get() throws InterruptedException {
        lock.lock();
        try {
            System.out.println("lock 可以具备可冲入性 -- get方法");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        new Thread(new NonReentrantLockDemo()).start();
    }


    static class NonReentrantLock {
        private volatile Boolean isLock = false;

        public synchronized void lock() throws InterruptedException {
            while (isLock) {
                wait();
            }
            isLock = true;
        }

        public synchronized void unlock() throws InterruptedException {
            isLock = false;
            notify();
        }

    }
}
